<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Cart as CartModel;
use app\common\model\GoodsSpec;

/**
 * 购物车接口
 * @ApiWeigh (86)
 */
class Cart extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 购物车列表
     * 
     * @ApiTitle    (购物车列表)
     * @ApiSummary  (获取当前用户的购物车商品列表)
     * @ApiMethod   (GET)
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": [{
          "id": 1,                        // 购物车ID
          "quantity": 2,                  // 商品数量
          "goods": {
            "id": 1,                      // 商品ID
            "title": "商品标题",          // 商品标题
            "cover_image": "商品图片",    // 商品图片
            "spec_id": 1,                 // 规格ID
            "spec_name": "规格名称",      // 规格名称
            "price": "10.00",             // 规格价格
            "original_price": "20.00",    // 规格原价
            "stock": 100                  // 规格库存
          }
        }]
      })
     */
    public function index()
    {
        // 获取会员折扣
        $discount = 1;
        if ($this->auth->id) {
            $user = \app\common\model\User::get($this->auth->id);
            if ($user->vip_expire_time > time()) {
                // 获取会员折扣配置
                $vipConfig = \app\common\model\VipConfig::where('id', 1)->find();
                if ($vipConfig) {
                    $discount = $vipConfig->discount;
                }
            }
        }

        $list = CartModel::with(['goods' => function($query) {
                $query->where('status', 1);
            }, 'spec'])
            ->where('user_id', $this->auth->id)
            ->select();
        
        $result = [];
        foreach($list as $item) {
            if(empty($item['goods'])) {
                continue;
            }
            // 计算会员价
            $price = round($item['spec']['price'] * $discount, 2);
            
            $result[] = [
                'id' => $item['id'],
                'quantity' => $item['quantity'],
                'goods' => [
                    'id' => $item['goods']['id'],
                    'title' => $item['goods']['title'],
                    'cover_image' => cdnurl($item['goods']['cover_image']),
                    'spec_id' => $item['spec']['id'],
                    'spec_name' => $item['spec']['spec_name'],
                    'price' => $price,
                    'original_price' => $item['spec']['price'],
                    'stock' => $item['spec']['stock'],
                    'freight_price' => $item['goods']['freight_price'] ?? '0.00'
                ]
            ];
        }
        
        $this->success('', $result);
    }

    /**
     * 添加购物车
     * 
     * @ApiTitle    (添加购物车)
     * @ApiSummary  (添加商品到购物车，如果已存在则增加数量)
     * @ApiMethod   (POST)
     * @ApiParams   (name="goods_id", type="integer", required=true, description="商品ID")
     * @ApiParams   (name="spec_id", type="integer", required=true, description="规格ID")
     * @ApiParams   (name="quantity", type="integer", required=true, description="数量")
     * @ApiReturn   ({
     "code": 1,
     "msg": "添加成功",
     "data": null
     })
     */
    public function add()
    {
        $goods_id = $this->request->post('goods_id');
        $spec_id = $this->request->post('spec_id');
        $quantity = $this->request->post('quantity', 1);

        // 检查规格
        $spec = GoodsSpec::where(['id' => $spec_id, 'goods_id' => $goods_id])->find();
        if (!$spec) {
            $this->error('商品规格不存在');
        }
        if ($spec->stock < $quantity) {
            $this->error('库存不足');
        }

        // 检查是否已在购物车
        $cart = CartModel::where([
            'user_id' => $this->auth->id,
            'goods_id' => $goods_id,
            'spec_id' => $spec_id
        ])->find();

        $cart_id = 0;
        if ($cart) {
            $cart->quantity = $cart->quantity + $quantity;
            $cart->save();
            $cart_id = $cart->id;
        } else {
            $newCart = CartModel::create([
                'user_id' => $this->auth->id,
                'goods_id' => $goods_id,
                'spec_id' => $spec_id,
                'quantity' => $quantity
            ]);
            $cart_id = $newCart->id;
        }

        // 您可以在这里使用 $cart_id，例如将其作为响应的一部分返回
        $this->success('操作成功', ['cart_id' => $cart_id]);
        //$this->success('添加成功');
    }

    /**
     * 更新购物车
     * 
     * @ApiTitle    (更新购物车)
     * @ApiSummary  (更新购物车商品数量)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="购物车ID")
     * @ApiParams   (name="quantity", type="integer", required=true, description="数量")
     * @ApiReturn   ({
     "code": 1,
     "msg": "更新成功",
     "data": null
     })
     */
    public function update()
    {
        $id = $this->request->post('id');
        $quantity = $this->request->post('quantity');

        $cart = CartModel::get($id);
        if (!$cart || $cart->user_id != $this->auth->id) {
            $this->error('记录不存在');
        }

        // 检查库存
        $spec = GoodsSpec::get($cart->spec_id);
        if ($spec->stock < $quantity) {
            $this->error('库存不足');
        }

        $cart->quantity = $quantity;
        $cart->save();

        $this->success('更新成功');
    }

    /**
     * 删除购物车
     * 
     * @ApiTitle    (删除购物车)
     * @ApiSummary  (删除购物车中的商品，支持批量删除)
     * @ApiMethod   (POST)
     * @ApiParams   (name="ids", type="string", required=true, description="购物车ID，多个用逗号分隔")
     * @ApiReturn   ({
     "code": 1,
     "msg": "success",
     "data": [{
       "id": 1,
       "goods_id": 1,
       "spec_id": 1,
       "quantity": 2,
       "goods": {
         "id": 1,
         "title": "商品标题",
         "cover_image": "商品图片"
       },
       "spec": {
         "id": 1,
         "spec_name": "规格名称",
         "price": "10.00",
         "original_price": "20.00",
         "stock": 100
       }
     }]
     })
     */
    public function delete()
    {
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error('参数错误');
        }

        CartModel::where('user_id', $this->auth->id)
            ->whereIn('id', explode(',', $ids))
            ->delete();

        $this->success('删除成功');
    }
}